#处理websvr请示
import math
import sqlite3
from ping3 import ping
def get_data(date):
    ret= {
        "series":[
            # {"name":"host1","data":[1,2,3,5,6,7,8,8,9]},
            # {"name":"host1","data":[9,8,7,6,5,4,3,2,1]},
            # {"name":"host1","data":[1,3,2,4,6,5,8,7,9]}
        ],
        "dates":[]
    }
    hosts={
        #host:{"name":"host1","data":[1,2,3,5,6,7,8,8,9]}
    }
    dates=[]

    map={'week':'%Y-%m-%d','year':'%Y-%m','hour':'%Y-%m-%d %H:%M','day':'%Y-%m-%d %H','min':'%Y-%m-%d %H:%M','sec':'%Y-%m-%d %H:%M:%S','month':'%Y-%m-%d'}
    sql =("select host,strftime( '%s', time ) as date ,avg(average) as v from ping "%map[date])
    sql+='where'
    if date=='year':
        sql += " time > datetime('now','-1 years') "
    elif date=='month':
         sql += " time > datetime('now','-1 months') "
    elif date=='hour':
        sql += " time > datetime('now','-1 hours') "
    elif date=='min':
        sql += " time > datetime('now','-10 minutes') "
    elif date=='week':
        sql += " time > datetime('now','-7 days') "
    elif date=='day':
        sql += " time > datetime('now','-1 days') "
    else:
        sql += " time > datetime('now','-60 seconds') "
    sql += "group by host,date order by date asc"
    
    try:
        con=sqlite3.connect('./ping.db')
        cur = con.cursor()
        rows=cur.execute(sql).fetchall()
        for row in rows:
            #创建主机序列
            host=row[0]
            if host not in hosts.keys():
                hosts[host]={"name":host,"data":[]}

            #创建日期
            date=row[1]
            if date not in dates:
                dates.append(date)
        #生成hosts
        for host in hosts.keys():
            for date in dates:
                found=False
                for row in rows:
                    _host=row[0]
                    _date=row[1]
                    if _host==host and _date==date:
                            hosts[host]['data'].append(math.ceil(row[2]))
                            found=True
                            break
                if not found:
                    hosts[host]['data'].append(0)
        #生成series
        for host in hosts.keys():
            ret["series"].append(hosts[host])
        ret['dates']=dates

    except Exception as ex:
        print(ex)
        ret['series']=[]
        ret['dates']=[]
    finally:
        cur.close()
        con.close()

    return ret

def ping_host(ip):
    """
    获取节点的延迟的作用
    :param node:
    :return:
    """
    ip_address = ip
    response = ping(ip_address)
    if response is not None:
        delay = float(response * 1000)
    else :
        delay=0
    return delay